<?php
class Utility
{      
	/**
	* Subsite first N word in the text as an intro text
	* 
	* @param mixed $originalString
	* @param mixed $wordsCount
	* @return string
	*/
	public static function getFirstWordsFromString($originalString, $wordsCount)
	{
		$words = explode(' ', stripslashes($originalString));
		if(count($words) > $wordsCount) 
		{
			$originalString = implode(' ', array_slice($words, 0, $wordsCount)).'...';
		} 
		return $originalString;
	}
		  
    public static function toAscii($from, $to, $str)
    {
        mb_internal_encoding("utf-8");        
        for ($i=0; $i<mb_strlen($from); $i++)
        {
            $fromChar = mb_substr($from, $i,1);
            $toChar = mb_substr($to, $i,1);
            $str = mb_eregi_replace("\\".$fromChar, $toChar, $str);
        }
        //return $str;
        return mb_convert_encoding($str,'ASCII');
    }
    
    /**
    * Create an URL alias for a string that may contain special characters
    * 
    * @param mixed $str
    * @return string
    */
    public static function urlAlias($str)
    {        
        /*$uni_from = ' ()!$?:,&+=><ÀàÁáÂâẢảÃãÄäÅåĀāĂăĄąǞǟǺǻÆæǼǽẠạẬậẶặẤấẮắẦầẪẫẨẩẲẳẴẵẰằḂḃĆćÇçČčĈĉĊċḐḑĎďḊḋĐđðǄǆÈèÉéĚěÊêỂểËëĒēĔĕĘęĖėƷʒǮǯẸẹỆệẺẻỄễẾếỀềẼẽḞḟǴǵĢģǦǧĜĝĞğĠġĤĥĦħÌìÍíÎîĨĩÏïĪīĬĭĮįİıỊịỈỉĴĵḰḱĶķǨǩĹĺĻļĽľĿŀŁłṀṁŃńŅņŇňÑñŉŊŋǊǌÒòÓóƠơỜờÔôÕõÖöŌōŎŏØøŐőǾǿŒœỌọỢợỘộỒồỞởỎỏỚớỐốỔổỖỗỠỡṖṗŔŕŖŗŘřɼŚśŞşŠšŜŝṠṡſßŢţŤťṪṫŦŧÞþÙùÚúÛûỦủŨũÜŮůŪūŬŭŲųŰűỤụỰựÙừỨứƯưỬửỮữẀẁẂẃŴŵẄẅỲỳÝýŶŷŸÿỴỵỸỹỶỷŹźŽžŻż`~;|{}[]`-–';    
        $uni_to = '-____________AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaBbCcCcCcCcCcDdDdDdDddDdEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeFfGgGgGgGgGgGgHhHhIiIiIiIiIiIiIiIiIiIiIiJjKkKkKkLlLlLlLlLlMmNnNnNnNnnNnNnOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoPpRrRrRrrSsSsSsSsSsSsTtTtTtTtTtUuUuUuUuUuUUuUuUuUuUuUuUuUuUuUuUuUuWwWwWwWwYyYyYyYyYyYyYyZzZzZz_________--';
        $from = "\\'\"/.@#%^*".$uni_from;
        $to   = '__________'.$uni_to;*/
        
        $uni_from = ' ()!$?:,&+=><ÀàÁáÂâẢảÃãÄäÅåĀāĂăĄąǞǟǺǻÆæǼǽẠạẬậẶặẤấẮắẦầẪẫẨẩẲẳẴẵẰằḂḃĆćÇçČčĈĉĊċḐḑĎďḊḋĐđðǄǆÈèÉéĚěÊêỂểËëĒēĔĕĘęĖėƷʒǮǯẸẹỆệẺẻỄễẾếỀềẼẽḞḟǴǵĢģǦǧĜĝĞğĠġĤĥĦħÌìÍíÎîĨĩÏïĪīĬĭĮįİıỊịỈỉĴĵḰḱĶķǨǩĹĺĻļĽľĿŀŁłṀṁŃńŅņŇňÑñŉŊŋǊǌÒòÓóƠơỜờÔôÕõÖöŌōŎŏØøŐőǾǿŒœỌọỢợỘộỒồỞởỎỏỚớỐốỔổỖỗỠỡṖṗŔŕŖŗŘřɼŚśŞşŠšŜŝṠṡſßŢţŤťṪṫŦŧÞþÙùÚúÛûỦủŨũÜŮůŪūŬŭŲųŰűỤụỰựÙừỨứƯưỬửỮữẀẁẂẃŴŵẄẅỲỳÝýŶŷŸÿỴỵỸỹỶỷŹźŽžŻż`~;|{}[]`-–';    
        $uni_to = '-            AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaBbCcCcCcCcCcDdDdDdDddDdEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeEeFfGgGgGgGgGgGgHhHhIiIiIiIiIiIiIiIiIiIiIiJjKkKkKkLlLlLlLlLlMmNnNnNnNnnNnNnOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoPpRrRrRrrSsSsSsSsSsSsTtTtTtTtTtUuUuUuUuUuUUuUuUuUuUuUuUuUuUuUuUuUuWwWwWwWwYyYyYyYyYyYyYyZzZzZz         --';
        $from = "\\'\"/.@#%^*".$uni_from;
        $to   = '          '.$uni_to;
       
        $newStr = strtolower(self::toAscii($from, $to, $str));
        return str_replace(array(' ','?'),'',$newStr);
    }
    
    public static function gererateSEO($str){

        $strReturn = $str;

        $marTViet=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
        "ằ","ắ","ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề"
        ,"ế","ệ","ể","ễ",
        "ì","í","ị","ỉ","ĩ",
        "ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
        ,"ờ","ớ","ợ","ở","ỡ",
        "ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
        "ỳ","ý","ỵ","ỷ","ỹ",
        "đ",
        "À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
        ,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
        "È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
        "Ì","Í","Ị","Ỉ","Ĩ",
        "Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
        ,"Ờ","Ớ","Ợ","Ở","Ỡ",
        "Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
        "Ỳ","Ý","Ỵ","Ỷ","Ỹ",
        "Đ",
        " ",",","?",";",":","/",".","'",'"',"(",")","&","%","#","_",'$',"!","@","^","*","+","=","|",'\\','{','}','[',']','<','>','`',"~",'“','”','’','–'
        );

        $marKoDau=array("a","a","a","a","a","a","a","a","a","a","a"
        ,"a","a","a","a","a","a",
        "e","e","e","e","e","e","e","e","e","e","e",
        "i","i","i","i","i",
        "o","o","o","o","o","o","o","o","o","o","o","o"
        ,"o","o","o","o","o",
        "u","u","u","u","u","u","u","u","u","u","u",
        "y","y","y","y","y",
        "d",
        "A","A","A","A","A","A","A","A","A","A","A","A"
        ,"A","A","A","A","A",
        "E","E","E","E","E","E","E","E","E","E","E",
        "I","I","I","I","I",
        "O","O","O","O","O","O","O","O","O","O","O","O"
        ,"O","O","O","O","O",
        "U","U","U","U","U","U","U","U","U","U","U",
        "Y","Y","Y","Y","Y",
        "D",
        "-","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
        );

        $strReturn = str_replace($marTViet,$marKoDau,$strReturn);
        $strReturn = strtolower($strReturn);

        // fix alias second time
        $allowedChars = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','x','y','z','v','w','s','0','1','2','3','4','5','6','7','8','9','-');
        $len = strlen($strReturn);
        $new_alias = '';
        for($i=0;$i<$len;$i++)
        {
            $char = substr($strReturn,$i,1);
            if (in_array($char,$allowedChars))
                $new_alias .= $char;
        }
        // loai bo cac dau gach ngang lien tiep
        $arr = array('--');
        for($j=0;$j<=33;$j++)
        {
            $last_ele = end($arr);
            $arr[] = $last_ele.'-';
        }
        $new_alias = trim(str_replace($arr,'-',$new_alias));
        $new_alias = trim(str_replace('--','-',$new_alias));
        
        return str_replace("?","",$new_alias);
    }
    
    /**
    * Append a path into an url to create a new url
    * 
    * Handle url in dir format (ends with /) or has extension (.php, .html, etc.)
    * 
    * @param mixed $url
    * @param mixed $path
    * @param bool $isDir Is the new url is a dir or has extension
    */
    public static function friendlyUrlAppend($url, $path, $isDir = false){
        if (strpos($path, '/') !== false){
            $steps = explode('/', $path);
            foreach($steps as &$step)
                $step = self::urlAlias($step);
            $path = implode('/', $steps);
        }else
            $path = self::urlAlias($path);
            
        if ($isDir && substr($path, strlen($path)-strlen(Settings::URL_EXT)) != Settings::URL_EXT)
            $path .= Settings::URL_EXT;
        else
            $path = trim($path,'/').'/';
        
        if (substr($url, strlen($url)-strlen(Settings::URL_EXT)) == Settings::URL_EXT)
            return substr($url,0,strlen($url) - strlen(Settings::URL_EXT)).$path;
        else{
            return rtrim($url,'/').'/'.$path;
        }
    }
    
    public static function urlAppendQuery($url, $params){
        $qs = '';
        foreach ($params as $key => $value)
            $qs .= '&'.$key.'='.urlencode($value);
        if (strpos($url, '?') !== false)
            return $url.$qs;
        else
            return $url.'?'.ltrim($qs, '&');
    }
    
    /**
    * check duplicate alias in database
    * 
    * @param mixed $model
    * @param String $alias
    * @param Boolean $flag
    */
    
    public function checkDuplicateAlias($model, $alias)
    {             
        $criteria = new CDbCriteria();
        $criteria->condition = "Alias = :alias";
        $criteria->params = array(':alias' => $alias);
        $objectList = $model->model()->count($criteria);        
            
        if($objectList > 0){                         
            for($i=2; $i<KBConstants::ALIAS_MAX_NUMBER; $i++){                
                $criteria->condition = "Alias = :alias";
                $criteria->params = array(':alias' => $alias . '_' . $i);
                $exist = $model->model()->count($criteria);
                if($exist == 0)
                    return $alias . '_' . $i;
            }
        }        
        return $alias;
    }
    
    /**
    * Create an alias
    * 
    * @param String $title
    * @param Int $id
    * @return String alias
    */
    
    public function createAlias($model, $title)
    {        
        $alias = trim($title);
        $alias = self::urlAlias($title);        
        return self::checkDuplicateAlias($model, $alias);
    }
    
    /**
    * Resize image
    * @param String $oldImagePath: Path of image you want to resize
    * @param String $newImagePath: new path for new image
    * @param String $width: Path of image you want to resize
    * @param String $height: Path of image you want to resize
    */
    public static function resize($oldImagePath, $newImagePath, $width, $height)
    {
        Yii::import('application.utilities.FlexImage');
        $fleximage = new FlexImage($oldImagePath);
        if ($fleximage->errorMessage != null)
            return $fleximage->errorMessage;
        else
            return $fleximage->resize($newImagePath, $width, $height, true);    
    }
    
    // get province list
    public static function getProvinceList()
    {
        if (!isset(Yii::app()->session['provinceList']))
        {
            Yii::import('deal.models.Province');
            $dealProvinces = Province::model()->findAll();
            $provinces = array();
            foreach($dealProvinces as $item)
                $provinces[] = $item->attributes;
            unset($dealProvinces);
            Yii::app()->session['provinceList'] = $provinces;    
        }
        
        return Yii::app()->session['provinceList'];
    }
    
    // get deal category list
    public static function getDealCategoryList()
    {
        if (!isset(Yii::app()->session['dealCategoryList']))
        {
            Yii::import('deal.models.DealCategory');
            $cri = new CDbCriteria();
            $cri->condition = "parent_id = 0";
            $cri->order = "category_id ASC";
            $dealCats = DealCategory::model()->findAll($cri);
            $cats = array();
            foreach($dealCats as $item)
            {
                $ele = $item->attributes;
                $ele['childrens'] = array();
                $criteria = new CDbCriteria();
                $criteria->condition = "parent_id = {$item->category_id}";
                $criteria->order = "category_id ASC";
                $childs = DealCategory::model()->findAll($criteria);
                foreach($childs as $child)
                {
                    $ele['childrens'][] = $child->attributes;    
                }
                $cats[] = $ele;
            }
            unset($dealCats);
            Yii::app()->session['dealCategoryList'] = $cats;    
        }

        return Yii::app()->session['dealCategoryList'];
    }
    
    public static function getCurrentProductType($controllerId)
    {
        $controllerId = strtolower($controllerId);
        $type = 'deal';
        if ($controllerId == 'promotionsite' || $controllerId == 'promotionuser')
            $type = 'promotion';
        elseif ($controllerId == 'vouchersite' || $controllerId == 'voucheruser')
            $type = 'voucher';
        return $type;
    }
    
    public static function getSourcesWithTags()
    {
        return array(
            '1' => array('zingdeal','zing deal','deal zing','deal.zing.vn'),
            '2' => array('nhommua','nhom mua','nhommua.com'),
            '3' => array('cungmua','cung mua','cungmua.com'),
            '4' => array('hotdeal','hot deal','hotdeal.vn'),
            '5' => array('muachung','mua chung','muachung.vn'),
            '6' => array('cucre','cuc re','cucre.vn'),
            '7' => array('phagia','pha gia','phagia.com.vn'),
            '8' => array('khuyenmaivang','khuyen mai vang','khuyenmaivang.vn'),
            '10' => array('vndoan','vn doan','vndoan.com'),
            '11' => array('runhau','ru nhau','runhau.vn'),
            '12' => array('muale','mua le','muale.vn'),
            '15' => array('remoingay','re moi ngay','remoingay.com'),
            '16' => array('51deal','51 deal','51deal.vn'),
            '17' => array('uudai','uu dai','uudai.vn'),
            '18' => array('datmua','dat mua','datmua.vn'),
            '19' => array('muamoingay','mua moi ngay','muamoingay.com'),
            '20' => array('hoishopping','hoi shopping','hoishopping.com'),
            '22' => array('necdeal','nec deal','necdeal.vn','necdeal.com'),
            '23' => array('dealtravel','deal travel','dealtravel.vn'),
            '24' => array('uudaigia','uu dai gia','uudaigia.com'),
            '25' => array('vivudeal','vi vu deal','vivudeal.com'),
            '26' => array('hottour','hot tour','hottour.vn'),
            '27' => array('vinadeal','vina deal','vinadeal.vn'),
            '28' => array('cungmuasam','cung mua sam','cungmuasam.net'),
            '29' => array('everyday','everyday.vn'),
            '30' => array('trangkhuyenmai','trang khuyen mai','trangkhuyenmai.vn'),
            '31' => array('nhanhmua','nhanh mua','nhanhmua.vn'),
            '32' => array('diadiemvang','dia diem vang','diadiemvang.net'),
            '33' => array(),
            '34' => array('dealsoc','deal soc','dealsoc.vn'),
            '35' => array('hoinhapdeal','hoi nhap deal','hoinhapdeal.vn'),
            '36' => array('retunggiay','re tung giay','retunggiay.vn'),
        );
    }
    
    public static function waterMarkImage($sourceImgPath, $desFolderPath)
    {
        $arrImageParts = explode('.',$sourceImgPath);
        $filetype = strtolower(end($arrImageParts));
        if($filetype == "gif") $image = @imagecreatefromgif($sourceImgPath);
        if(in_array($filetype,array('jpg','jpeg'))) $image = @imagecreatefromjpeg($sourceImgPath);
        if($filetype == "png") $image = @imagecreatefrompng($sourceImgPath);
        if (empty($image)) return '';
        $watermark = @imagecreatefrompng('images/watermark.gif'); // file watermark
        $imagewidth = imagesx($image);
        $imageheight = imagesy($image);
        $watermarkwidth = imagesx($watermark);
        $watermarkheight = imagesy($watermark);
        $startwidth = (($imagewidth - $watermarkwidth)/25);
        $startheight = (($imageheight - $watermarkheight)/20);
        imagecopy($image, $watermark,  $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
        // lay filename
        $arrImageParts2 = explode('/',$sourceImgPath);
        $filename = 'mark_'.trim(end($arrImageParts2)); 
        imagejpeg($image, $desFolderPath.'/'.$filename);
        imagedestroy($image);
        imagedestroy($watermark);
        if (file_exists($sourceImgPath)) unlink($sourceImgPath);
        return $filename;    
    }
}
?>